<?php
/**
 * 作用：微信门店处理模块
 * 作者: shijy@soe-soe.com
 * 日期: 2016/4/27 15:41
 * 公司: 浙江宣逸网络科技有限公司<www.soe-soe.com>
 */
namespace Common\Model;
class WeixinStoreModel extends BaseModel{

	//微信门店是否可用状态
	const WEIXIN_STORE_AVAILABLE_STATE_ERROR	=1;//1 表示系统错误
	const WEIXIN_STORE_AVAILABLE_STATE_CHECK	=2;//2 表示审核中
	const WEIXIN_STORE_AVAILABLE_STATE_PASS		=3;//3 审核通过
	const WEIXIN_STORE_AVAILABLE_STATE_UNPASS	=4;//4 审核驳回。当该字段为1、2、4 状态时，poi_id 为空


	/**
	 * 查询门店列表
	 * url:http://mp.weixin.qq.com/wiki/16/8f182af4d8dcea02c56506306bdb2f4c.html
	 * Author: shijy
	 * @param int $page
	 * @param int $perpage
	 * @return mixed
	 */
	public static function get_poilist($page=1,$perpage=50){
		$start=($page-1) * $perpage;
		$url="https://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=";
		$data='{"begin":'.$start.',"limit":'.$perpage.'}';
		$result= WeixinModel::send($url,$data);

		if($result['status']!=0){
			return $result;
		}
		$data=array();
		foreach ($result['data']['business_list'] as $one){
			$tmp=array(
				'business_name'		=>$one['base_info']['business_name'],
				'branch_name'		=> $one['base_info']['branch_name'],
				'address'			=> $one['base_info']['address'],
				'poi_id'			=> $one['base_info']['poi_id'],
				'sid'				=> $one['base_info']['sid'],
				'available_state'	=> $one['base_info']['available_state']
			);
			$data[]=$tmp;
		}
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataSuccess['data']=$data;
		$dataSuccess['total']=$result['data']['total_count'];
		return $dataSuccess;
	}


	/**
	 * 获取全部门店
	 * Author: shijy
	 * @return mixed
	 */
	public static function get_all_poilist(){
		$pageSize=50;
		$data=self::get_poilist(0,50);
		if ($data['total']<$pageSize){
			return $data;
		}

		$stores=$data['data'];
		$pageCount=ceil($data['total']/$pageSize);
		for($page=1;$page<$pageCount;$page++){
			$offset = $page * $pageSize;
			$next=self::get_poilist($offset,$pageSize);
			$stores=array_merge($stores,$next['data']);
		}
		$data['data']=$stores;
		return $data;
	}


	/**
	 * 根据可用状态获取门店列表
	 * Author: shijy
	 * @param $weixinAvailableState
	 * @return mixed
	 */
	public static function getStoreByAvailableState($weixinAvailableState){
		$result=self::get_all_poilist();
		if($result['status']!=0){
			return $result;
		}
		foreach($result['data'] as $k=>$v){
			if($v['available_state']!=$weixinAvailableState){
				unset($result['data'][$k]);
			}
		}
		return $result;
	}

	public static function getStoreUseFull(){
		return self::getStoreByAvailableState(self::WEIXIN_STORE_AVAILABLE_STATE_PASS);
	}
}